package com.drcoffee.drcoffeemall.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.drcoffee.drcoffeemall.entry.Result;
import com.drcoffee.drcoffeemall.entry.Trade;
import com.drcoffee.drcoffeemall.mapper.AfterSaleMapper;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class PayRefundUtil {

    @Autowired
    AfterSaleMapper afterSaleMapper;

    // 支付宝支付参数配置 //
    @Value("${alipay.app_id}")
    private String ali_app_id;//应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号

    //商户私钥，您的PKCS8格式RSA2私钥
    @Value("${alipay.merchant_private_key}")
    private String ali_merchant_private_key;

    //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    @Value("${alipay.alipay_public_key}")
    private String ali_alipay_public_key;

    @Value("${alipay.sign_type}")
    private String ali_sign_type;//签名方式

    @Value("${alipay.charset}")
    private String ali_charset;//字符编码格式

    @Value("${alipay.gateway_url}")
    private String ali_gateway_url;//支付宝网关

    /**
     * 商户号
     */
    @Value("${wechat.merchantId}")
    private String wx_merchantId = "1489444742";

    /**
     * 商户API私钥路径
     */
    @Value("${wechat.privateKeyPath}")
    private String wx_privateKeyPath;

    /**
     * 商户证书序列号
     */
    @Value("${wechat.merchantSerialNumber}")
    private String wx_merchantSerialNumber;

    /**
     * 商户APIV3密钥
     */
    @Value("${wechat.apiV3Key}")
    private String wx_apiV3Key;

    /**
     * 微信退款
     * 详情见文档：https://pay.weixin.qq.com/docs/merchant/apis/native-payment/create.html
     */
    public Result weChatRefund(String transaction_id, String out_trade_no, String out_refund_no, AmountReq amount, String flow_four) {
        try {
            // 初始化商户配置
            Config config =
                    new RSAAutoCertificateConfig.Builder()
                            .merchantId(wx_merchantId)
                            .privateKeyFromPath(wx_privateKeyPath)
                            .merchantSerialNumber(wx_merchantSerialNumber)
                            .apiV3Key(wx_apiV3Key)
                            .build();
            // 初始化service
            RefundService service = new RefundService.Builder().config(config).build();
            CreateRequest request = new CreateRequest();
            request.setTransactionId(transaction_id); // 微信支付订单号
            request.setOutTradeNo(out_trade_no); // 商户订单号
            request.setOutRefundNo(out_refund_no); // 商户退款单号
            request.setAmount(amount);
            request.setNotifyUrl("http://mall.dr-coffee.com/prod-api/wechatPay/notifyRefund");// 退款通知
            Refund refund = service.create(request);
            System.out.println(refund);
            if (refund.getStatus() == Status.SUCCESS || refund.getStatus() == Status.PROCESSING) {
                Integer tradeNum = afterSaleMapper.getTradeNum(out_trade_no, "O");
                Date parse = new Date();
                if (refund.getSuccessTime() != null) {
                    parse = new SimpleDateFormat("yyyy-MM-dd").parse(refund.getSuccessTime());
                }
                if (tradeNum == 0) {
                    Trade trade = new Trade(null,
                            refund.getOutTradeNo(),
                            parse,
                            refund.getRefundId(), refund.getOutRefundNo(),
                            new BigDecimal(refund.getAmount().getRefund()).divide(new BigDecimal(100)),
                            "O", 1,null,null);
                    afterSaleMapper.insertTrade(trade);
                    afterSaleMapper.setAfterSaleStatus(out_refund_no, 7, ",flow_four = ", flow_four);
                }
                return new Result(1, "SUCCESS", "执行成功，退款成功", null);
            } else {
                return new Result(-1, "WARN", "执行成功,退款异常", refund.getStatus());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    /**
     * 支付宝退款
     */
    public Result alipayRefund(String trade_no, String refund_amount, String out_refund_no, String flow_four) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(ali_gateway_url, ali_app_id, ali_merchant_private_key, "json", ali_charset, ali_alipay_public_key, ali_sign_type);
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            JSONObject bizContent = new JSONObject();
            // 根据订单编号查询交易记录
            bizContent.put("trade_no", trade_no); // 支付交易号
            bizContent.put("refund_amount", refund_amount); // 退款金额
            bizContent.put("out_request_no", out_refund_no); // 退款号
            request.setBizContent(bizContent.toString());
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                // 存储交易记录
                Trade trade = new Trade(null,
                        response.getOutTradeNo(),
                        response.getGmtRefundPay(),
                        response.getTradeNo(),
                        out_refund_no,
                        new BigDecimal(response.getRefundFee()),
                        "O",
                        2,null,null);
                afterSaleMapper.insertTrade(trade);
                afterSaleMapper.setAfterSaleStatus(out_refund_no, 7, ",flow_four = ", flow_four);
                return new Result(1, "SUCCESS", "执行成功，退款成功", null);
            } else {
                return new Result(-1, "WARN", "执行成功,退款异常", response.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }
}
